package com.jvm.interpreter;

import com.jvm.classfile.Const;
import com.jvm.classfile.model.Method;

import java.util.Map;

/**
 * @program: diy_simple_jvm
 * @description: 解释器
 * @author: CaoYong
 * @create: 2021-07-08 10:25
 **/
public class Interpreter {

    /**
     * 解释器通过栈帧循环执行指令列表中的指令
     * @param frame
     * @param instructions
     */
    public static void run(Frame frame, Map<Integer, Instruction> instructions) {
        do {
            Instruction instruction = instructions.get(frame.pc);
            instruction.eval(frame);
        } while (instructions.containsKey(frame.pc));
    }
    /**
     * 同步执行指定方法
     */
    public static void execute(Method method) {
        final ExecEnv env = MetaSpace.getMainEnv();
        Frame newFrame = new Frame(method);
        final Frame old = env.topFrame();
        // 传参
        final int slots = method.getArgSlotSize();
        for (int i = slots - 1; i >= 0; i--) {
            newFrame.set(i, old.pop());
        }
        execute(newFrame);
    }

    /**
     * 同步执行栈帧
     */
    public static void execute(Frame newFrame) {
        final ExecEnv env = MetaSpace.getMainEnv();
        env.pushFrame(newFrame);

        newFrame.stat = Const.FAKE_FRAME;
        do {
            Frame frame = env.topFrame();
            Instruction instruction = frame.getInstruction();
            instruction.eval(frame);
        } while (newFrame.stat == Const.FAKE_FRAME);
    }



}
